<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<c:set var="basePath" value="${pageContext.request.contextPath}"/>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    request.setAttribute("basePath", basePath);
%>
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>user</title>
    <script src="../../plugins/jquery.1.12.4.min.js"></script>
    <link rel="stylesheet" href="../../plugins/bootstrap-3.3.0/css/bootstrap.min.css">
    <script src="../../plugins/bootstrap-3.3.0/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../../plugins/bootstrap-table-1.11.0/bootstrap-table.min.css">
    <script src="../../plugins/bootstrap-table-1.11.0/bootstrap-table.min.js"></script>
    <link href="../../plugins/waves-0.7.5/waves.min.css" rel="stylesheet"/>
    <script src="../../plugins/waves-0.7.5/waves.min.js"></script>
    <script src="../../plugins/bootstrap-table-1.11.0/locale/bootstrap-table-zh-CN.min.js"></script>
    <link rel="stylesheet" href="../../plugins/jquery-confirm/jquery-confirm.min.css">
    <script src="../../plugins/jquery-confirm/jquery-confirm.min.js"></script>
    <link rel="stylesheet" href="../../css/metroStyle/metroStyle.css" type="text/css">
    <script type="text/javascript" src="../../js/jquery.ztree.core.js"></script>
    <script type="text/javascript" src="../../js/jquery.ztree.excheck.js"></script>
    <script type="text/javascript" src="../../js/jquery.ztree.exedit.js"></script>
    <link rel="stylesheet" href="../../plugins/awesome-bootstrap-checkbox/awesome-bootstrap-checkbox.css">
    <script src="../../plugins/select2/js/select2.min.js"></script>
    <link rel="stylesheet" href="../../plugins/select2/css/select2.min.css">

    <script src="../../js/common.js"></script>
    <style>
        #main{padding:1% 2% 2%;background-color:#f5f5f5;}
        .form-group{padding: 10px 20px 0 20px}
    </style>
</head>
<body>
<div id="main" >
    <div id="toolbar" class="btn-group">
        <shiro:hasPermission name="user:add">
            <button id="btn_add" type="button" class="btn btn-default" data-toggle="modal" data-target="#addModal" >
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增用户
            </button>
        </shiro:hasPermission>
        <shiro:hasPermission name="user:update">
            <button id="btn_edit" type="button" class="btn btn-default" onclick="updateAction()">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>编辑用户
            </button>
        </shiro:hasPermission>
        <shiro:hasPermission name="user:allocation">
            <button id="btn_allocation" type="button" class="btn btn-default" onclick="allocation()">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>分配角色
            </button>
        </shiro:hasPermission>
        <shiro:hasPermission name="user:read">
            <button id="btn_excelWrite" type="button" class="btn btn-default" onclick="excelWrite()">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>导出表格
            </button>
        </shiro:hasPermission>
        <shiro:hasPermission name="user:delete">
            <button id="btn_delete" type="button" class="btn btn-default" onclick="deleteAction()">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除用户
            </button>
        </shiro:hasPermission>
        <div class="pull-right" id="query-form" style="padding-bottom:10px;margin-left:51em;">
            <div style="float:left;margin-right:5px;">
                <input id="search_nickname" name="description" placeholder='昵称' type="text"
                       style="float:left;width:150px;margin-right:5px;" v-model="description"
                       class="form-control">
            </div>
            <div class="btn-group">
                <button id="btn_search" type="button" class="btn btn-primary btn-space">
                    <span class="fa fa-search" aria-hidden="true" class="btn-icon-space"></span>查询
                </button>
                <%--onclick="resetSearch()"--%>
                <button id="btn_reset"  type="button" class="btn btn-default btn-space">
                    <span class="fa fa-eraser" aria-hidden="true" class="btn-icon-space"></span>重置
                </button>
            </div>
        </div>

    </div>
    <!-- 新增模态框（Modal）-->
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog"  aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;
                    </button>
                    <h4 class="modal-title" >
                        <strong>新增用户</strong>
                    </h4>
                </div>
                <div class="form-group" >
                    <label for="addUserName">账号</label>
                    <input id="addUserName" type="text" class="form-control" name="addUserName" maxlength="20">
                </div>
                <div class="form-group">
                    <label for="addPwd">密码</label>
                    <input id="addPwd" type="text" class="form-control" name="addPwd" maxlength="20">
                </div>
                <div class="form-group">
                    <label for="addNick">昵称</label>
                    <input id="addNick" type="text" class="form-control" name="addNick" maxlength="300">
                </div>
                <div class="form-group">
                    <label for="addAvatar">头像</label>
                    <img id="addImg" src="${basePath}${imgSrc}" style="width:50px;height:50px;display:none;"/>
                    <input id="addAvatar" type="file" name="addAvatar" maxlength="300">
                </div>
                <div class="form-group">
                    <label >状态</label>
                    <div class="radio">
                        <div class="radio radio-inline radio-success">
                            <input id="addStatus_0" type="radio" name="addStatus" value="0" checked>
                            <label for="addStatus_0">正常 </label>
                        </div>
                        <div class="radio radio-inline">
                            <input id="addStatus_1" type="radio" name="addStatus" value="1">
                            <label for="addStatus_1">锁定 </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                    </button>
                    <button id="createUser" type="button" class="btn btn-primary">
                        确定新增
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
    <!-- 编辑模态框（Modal）-->
    <div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;
                    </button>
                    <h4 class="modal-title" >
                        <strong>编辑用户</strong>
                    </h4>
                </div>
                <div class="modal-body">
                    <label id="updateId" value="" style="display:none"></label>
                    <div class="form-group" >
                        <label for="updateUserName">账号</label>
                        <input id="updateUserName" type="text" class="form-control" name="updateUserName" maxlength="20" value="">
                    </div>
                    <%--<div class="form-group">--%>
                        <%--<label for="updatePwd">密码</label>--%>
                        <%--<input id="updatePwd" type="text" class="form-control" name="updatePwd" maxlength="20" value="">--%>
                    <%--</div>--%>
                    <div class="form-group">
                        <label for="updateNick">昵称</label>
                        <input id="updateNick" type="text" class="form-control" name="updateNick" maxlength="300" value="">
                    </div>
                    <div class="form-group">
                        <label for="updateAvatar">头像</label>
                        <input id="updateAvatar" type="text" class="form-control" name="updateAvatar" maxlength="300" value="">
                    </div>
                    <div class="form-group">
                        <label >状态</label>
                        <div class="radio">
                            <div class="radio radio-inline radio-success">
                                <input id="updateStatus_0" type="radio" name="updateStatus" value="0">
                                <label for="updateStatus_0">正常 </label>
                            </div>
                            <div class="radio radio-inline">
                                <input id="updateStatus_1" type="radio" name="updateStatus" value="1">
                                <label for="updateStatus_1">锁定 </label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                    </button>
                    <button id="updateUser" type="button" class="btn btn-primary">
                        提交更改
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>

    <!-- 分配模态框（Modal）-->
    <div class="modal fade" id="allcateModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;
                    </button>
                    <h4 class="modal-title" >
                        <strong>分配用户</strong>
                    </h4>
                </div>
                <div class="modal-body">
                    <tr>
                        <td>
                            <select class="combox" id="sel_recommender" name="recommenderId">
                                <option value="chioc">请选择...</option>
                            </select>
                        </td>
                    </tr>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                    </button>
                    <button id="allocateUser" type="button" class="btn btn-primary">
                        提交更改
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>

    <table id="table" style="font-size: 14px;"></table>
</div>

<script>
    var $table = $('#table');
    $('#table').bootstrapTable({
        url: '${basePath}/user/list',
        contentType: "application/x-www-form-urlencoded",//必须要有！！！！
        height:getHeight(), //高度调整
        striped: true, // 是否显示行间隔色
        // dataField: "res",//bootstrap table 可以前端分页也可以后端分页，这里
        //我们使用的是后端分页，后端分页时需返回含有total：总记录数,这个键值好像是固定的
        //rows： 记录集合 键值可以修改  dataField 自己定义成自己想要的就好
        // search: true,
        showRefresh: true,
        showColumns: true,
        minimumCountColumns: 2,
        clickToSelect: true,
        // detailView: true,
        paginationLoop: false,
        sidePagination: 'server',//指定服务器端分页
        silentSort: false,
        smartDisplay: false,
        // queryParamsType:'limit',//查询参数组织方式
        // queryParams:queryParams,//请求服务器时所传的参数
        escape: true,
        // searchOnEnterKey: true,
        detailFormatter: 'detailFormatter',
        toolbar: "#toolbar", //指定工具栏
        // toolbarAlign:'right',//工具栏对齐方式
        buttonsAlign:'right',//按钮对齐方式
        uniqueId: "id",
        pageSize: "10",
        pagination: true, // 是否分页
        sortable: true, // 是否启用排序
        cardView: false,                    //是否显示详细视图
        detailView: false,                   //是否显示父子表
        columns: [
            {field: 'ck', checkbox: true,width:70},
            {field: 'id',title: '编号',align:'center'},
            {field: 'username',title: '账号',align:'center'},
            {field: 'nickname',title: '昵称',align: 'center'},
            {field: 'avatar',title: '头像',align: 'center'},
            {field: 'title',title: '角色',align: 'center'},
            {field: 'lastLoginTime',title: '最近登录',align: 'center'},
            {field: 'status',title: '状态',align: 'center',formatter: statusFormatter},
            {field: 'createTime',title: '创建时间',align: 'center'},
            {field: 'updateTime',title: '更新时间',align: 'center'},
            {field: 'operation',title: '操作',width:200,align: 'center',valign: 'middle',formatter: actionFormatter, clickToSelect: false},
        ]
    });
    //状态的格式化
    function statusFormatter(value, row, index) {
        if(value == 1){
            return '锁定';
        }else{
            return '正常';
        }
    }

    // //请求服务数据时所传参数
    // function queryParams(params){
    //     return{
    //         //每页多少条数据
    //         pageSize: params.limit,
    //         //请求第几页
    //         pageNum:params.pageNumber,
    //         nickname:$('#search_nickname').val(),
    //     }
    // }

    //查询按钮事件
    $('#btn_search').click(function(){
        var nickname = $('#search_nickname').val();
        $('#table').bootstrapTable('refresh', {url: '${basePath}/user/searchUser?nickname='+nickname});
    })

    //操作栏的格式化
    function actionFormatter(value, row, index) {
        return [
            '<a href="javascript:;" onclick="updateAction()" data-toggle="tooltip" title="Edit" class="btn btn-xs btn-primary btn-update" style="background-color: grey;"><i class="glyphicon glyphicon-edit"></i>编辑</a>',
            '&nbsp; <a href="javascript:;" onclick="deleteAction()" data-toggle="tooltip" title="Remove" class="btn btn-xs btn-danger btn-remove"  style="background-color: black;"><i class="glyphicon glyphicon-remove"></i>删除</a>'
            // '<a class="update" href="javascript:;" onclick="updateAction()" data-toggle="tooltip" title="Edit"><i class="glyphicon glyphicon-edit"></i></a>　',
            // '<a class="delete" href="javascript:;" onclick="deleteAction()" data-toggle="tooltip" title="Remove"><i class="glyphicon glyphicon-remove"></i></a>'
        ].join('');
    }

    //新增
    $("#addAvatar").change(function () {
        var data=new FormData();//创建表单对象
        data.append("file",$('#addAvatar')[0].files[0]);
        $.ajax({       
            url:'${basePath}/user/uploadImg',
            type:"post",
            dataType:'json',
            contentType: false,
            processData: false,
            mimeType: "multipart/form-data",
            data:data,
            success:function (result) {
                if (result.result == "success"){
                    var imgSrc = result.imgSrc;
                    $('#addImg').attr("src",imgSrc);
                    $('#addImg').css("display","block");
                }else{
                    alert("fail");
                }
            }
        })
    })

    $("#createUser").click(function () {
        var addUserName = $("#addUserName").val();
        var addPwd = $("#addPwd").val();
        var addNick = $("#addNick").val();
        var addAvatar = $('#addImg').attr("src");
        var addStatus = $('input:radio[name="addStatus"]:checked').val();
        var user = {username:addUserName,password:addPwd,nickname:addNick,avatar:addAvatar,status:addStatus};
        $.ajax({
            url:'${basePath}/user/create',
            type:"post",
            dataType:'json',
            data:user,
            success:function (result) {
                if (result.result == "success"){
                    $('#addModal').modal('hide');
                    $("#table").bootstrapTable('refresh');
                }else{
                    alert("fail");
                }
            }
        })
    })

    // 编辑
    function updateAction() {
        var row = $table.bootstrapTable('getSelections');
        if (row.length != 1) {
            $.confirm({
                type: 'blue',
                title: false,
                content: '请选择一条记录！',
                autoClose: 'cancel|3000',
                backgroundDismiss: true,
                buttons: {
                    cancel: {
                        text: '取消',
                        btnClass: 'waves-effect waves-button'
                    }
                }
            });
        } else {
            // alert(rows[0].ck+rows[0].id+rows[0].name+rows[0].title+rows[0].description+rows[0].available+rows[0].operation);
            var setId = row[0].id;
            var setUsername = row[0].username;
            var setNickname = row[0].nickname;
            var setAvatar = row[0].avatar;
            var setStatus = row[0].status;

            $("#updateUserName").val(setUsername);
            $("#updateNick").val(setNickname);
            $("#updateAvatar").val(setAvatar);
            if(setStatus == 0){
                $("#updateStatus_0").prop("checked", true);
            }else if(setStatus == 1){
                $('#updateStatus_1').prop("checked", true);
            }
            $('#updateModal').modal('show');

            $("#updateUser").off("click").on("click",function(){
                var updateUserName = $("#updateUserName").val();
                var updateNick = $("#updateNick").val();
                var updateAvatar = $("#updateAvatar").val();
                var updateStatus = $('input:radio[name="updateStatus"]:checked').val();
                var role = {id:setId,username:updateUserName,nickname:updateNick,avatar:updateAvatar,status:updateStatus}
                $.ajax({
                    url:'${basePath}/user/update',
                    type:"post",
                    dataType:'json',
                    data:role,
                    success:function (result) {
                        if (result.result == "success"){
                            $('#updateModal').modal('hide');
                            $('#table').bootstrapTable('refresh');
                        }else{
                            alert("fail");
                        }
                    }
                })
            });
        }
    }

    // 分配角色
    function allocation() {
        var row = $table.bootstrapTable('getSelections');
        if (row.length != 1) {
            $.confirm({
                type: 'blue',
                title: false,
                content: '请选择一条记录！',
                autoClose: 'cancel|3000',
                backgroundDismiss: true,
                buttons: {
                    cancel: {
                        text: '取消',
                        btnClass: 'waves-effect waves-button'
                    }
                }
            });
        } else {
            $(".subOption").remove();
            $.ajax({
                type:'get',
                url:'${basePath}/role/list?offset=10&limit=10',
                dataType:'json',
                success:function (data) {
                    var list = data.rows;
                    for(var i = 0;i<list.length;i++){
                        if(row[0].title == list[i].title){
                            $("#sel_recommender").append("<option id="+list[i].id+' class="subOption"'+" value=\"mingren\" selected>"+list[i].title+"</option>");
                        }else{
                            $("#sel_recommender").append("<option id="+list[i].id+' class="subOption"'+" value=\"mingren\">"+list[i].title+"</option>");
                        }
                    }
                }
            });
            $('#sel_recommender').select2({
                placeholder: "请选择",
                width:'256px'
            });
            $('#allcateModal').modal('show');

            $("#allocateUser").off("click").on("click",function(){
                var roleId = $("#sel_recommender").find("option:selected").attr('id');
                $.ajax({
                    url:'${basePath}/user/uptUserRole?userId='+row[0].id+'&roleId='+roleId,
                    type:"get",
                    dataType:'json',
                    success:function (result) {
                        if (result.result == "success"){
                            $('#allcateModal').modal('hide');
                            $("#table").bootstrapTable('refresh');
                        }else{
                            alert("fail");
                        }
                    }
                })
            })
        }
    }

    // 导出表格
    function excelWrite() {
        var row = $table.bootstrapTable('getSelections');
        if (row.length == 0) {
            $.confirm({
                type: 'blue',
                title: false,
                content: '请选择至少一条记录！',
                autoClose: 'cancel|3000',
                backgroundDismiss: true,
                buttons: {
                    cancel: {
                        text: '取消',
                        btnClass: 'waves-effect waves-button'
                    }
                }
            });
        } else {
            var excelData= [];
            for(var i=0;i<row.length;i++){
                var excelCell = {id:row[i].id,username:row[i].username,nickname:row[i].nickname,title:row[i].title,lastLoginTime:row[i].lastLoginTime,status:row[i].status,createTime:row[i].createTime,updateTime:row[i].updateTime}
                excelData.push(excelCell);
            }
            window.location.href = '${basePath}/excel/demo?excelData='+JSON.stringify(excelData);
        }
    }
    // 删除
    var deleteDialog;
    function deleteAction() {
        var rows = $table.bootstrapTable('getSelections');
        if (rows.length == 0) {
            $.confirm({
                type: 'blue',
                title: false,
                content: '请至少选择一条记录！',
                autoClose: 'cancel|3000',
                backgroundDismiss: true,
                buttons: {
                    cancel: {
                        text: '取消',
                        btnClass: 'waves-effect waves-button'
                    }
                }
            });
        } else {
            deleteDialog = $.confirm({
                type: 'red',
                animationSpeed: 300,
                title: false,
                content: '确认删除该角色吗？',
                buttons: {
                    confirm: {
                        text: '确认',
                        btnClass: 'waves-effect waves-button',
                        action: function () {
                            var ids = new Array();
                            for (var i in rows) {
                                ids.push(rows[i].id);
                            }
                            $.ajax({
                                type: 'get',
                                url: '${basePath}/user/delete/' + ids,
                                success: function(result) {
                                    if (result.result != 'success') {
                                        $.confirm({
                                            theme: 'dark',
                                            animation: 'rotateX',
                                            closeAnimation: 'rotateX',
                                            title: false,
                                            content: '删除失败',
                                            buttons: {
                                                confirm: {
                                                    text: '确认',
                                                    btnClass: 'waves-effect waves-button waves-light'
                                                }
                                            }
                                        });
                                    } else {
                                        $.confirm({
                                            theme: 'dark',
                                            animation: 'rotateX',
                                            closeAnimation: 'rotateX',
                                            title: false,
                                            content: '删除成功',
                                            buttons: {
                                                confirm: {
                                                    text: '确认',
                                                    btnClass: 'waves-effect waves-button waves-light'
                                                }
                                            }
                                        });
                                        $('#table').bootstrapTable('refresh');
                                    }
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    $.confirm({
                                        theme: 'dark',
                                        animation: 'rotateX',
                                        closeAnimation: 'rotateX',
                                        title: false,
                                        content: textStatus,
                                        buttons: {
                                            confirm: {
                                                text: '确认',
                                                btnClass: 'waves-effect waves-button waves-light'
                                            }
                                        }
                                    });
                                }
                            });
                        }
                    },
                    cancel: {
                        text: '取消',
                        btnClass: 'waves-effect waves-button'
                    }
                }
            });
        }
    }
</script>
</body>

</html>